package com.fly.procode.ui;

import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/**
 * 
 * 工具UI简化版本，Swing技术实现
 * 
 * @author 00fly
 * @version [版本号, 2023年3月3日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class ProCodeToolSimple extends JFrame
{
    private static final long serialVersionUID = -2145267777297657212L;
    
    JFrame frame = this;
    
    public ProCodeToolSimple()
    {
        initComponent();
        this.setVisible(true);
        this.setResizable(true);
        this.setAlwaysOnTop(true);
        this.setTitle("代码恢复工具 V1.0");
        this.setBounds(400, 200, 1200, 550);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        try
        {
            // 设定用户界面的外观
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);
        }
        catch (Exception e)
        {
        }
    }
    
    /**
     * 组件初始化
     * 
     * @see [类、类#方法、类#成员]
     */
    private void initComponent()
    {
        // 加载图标
        URL url = getClass().getResource("/image/icon.gif");
        if (url != null)
        {
            this.setIconImage(getToolkit().createImage(url));
        }
        
        JTextArea textArea = new JTextArea();
        textArea.setToolTipText("请输入全部待恢复代码");
        
        // JTextArea不自带滚动条，因此就需要把文本区放到一个滚动窗格中
        JScrollPane scroll = new JScrollPane(textArea);
        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        
        JButton button = new JButton("开始恢复代码");
        this.add(scroll, BorderLayout.CENTER);
        this.add(button, BorderLayout.SOUTH);
        button.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent event)
            {
                try
                {
                    String dir = new File("" + System.currentTimeMillis()).getCanonicalPath() + File.separator;
                    createSourceFile(textArea.getText(), dir);
                    JOptionPane.showMessageDialog(frame, "恢复文件到目录: " + dir + " 成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
                }
                catch (Exception e)
                {
                    JOptionPane.showMessageDialog(frame, e.getMessage(), "系統异常", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
    }
    
    /**
     * 恢复文件至dir
     * 
     * @param text
     * @param dir
     */
    private void createSourceFile(String text, String dir)
    {
        if (text == null || text.trim().length() == 0)
        {
            throw new RuntimeException("输入代码不能为空");
        }
        String[] textArr = text.split("\n");
        BufferedWriter writer = null;
        for (String line : textArr)
        {
            try
            {
                if (line.trim().startsWith("//goto "))
                {
                    // close old file
                    if (writer != null)
                    {
                        writer.close();
                    }
                    // creat new file
                    int pos = line.indexOf("//goto ") + 7;
                    File file = new File(dir + line.substring(pos).replace("\\", File.separator));
                    file.getParentFile().mkdirs();
                    OutputStream os = new FileOutputStream(file);
                    writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8), 8192);
                }
                else
                {
                    if (writer != null)
                    {
                        writer.write(line);
                        writer.newLine();
                    }
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        try
        {
            if (writer != null)
            {
                writer.close();
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(() -> new ProCodeToolSimple());
    }
}
